package com.ai.deepseekspring.service.impl;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;

import com.ai.deepseekspring.Enum.ResponseEnum;
import com.ai.deepseekspring.Result.R;
import com.ai.deepseekspring.domain.dto.UserDTO;
import com.ai.deepseekspring.domain.dto.UserRegisterDTO;
import com.ai.deepseekspring.domain.po.User;
import com.ai.deepseekspring.domain.vo.UserVO;
import com.ai.deepseekspring.mapper.UserMapper;
import com.ai.deepseekspring.service.UserService;
import com.ai.deepseekspring.utils.TokenUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {


    @Override
    public UserVO login(UserDTO userDTO) {
        String password = userDTO.getPassword();
        String username = userDTO.getUsername();


        User user = lambdaQuery().eq(User::getUsername, username).one();


        if (user != null && user.getPassword().equals(password)) {
            UserVO userVO = new UserVO();
            JSONObject json = JSONUtil.createObj()
                    .put("id", user.getId())
                    .put("name", username);


            String token = TokenUtil.createToken(json);user.setToken(token);
            userVO.setId(user.getId());
            userVO.setUsername(user.getUsername());
            userVO.setToken(user.getToken());
            return userVO;
        }
        return null;
    }

    @Override
    public R register(UserRegisterDTO userRegisterDTO) {
        String username = userRegisterDTO.getUsername();
        String password = userRegisterDTO.getPassword();
        String confirmPassword = userRegisterDTO.getConfirmPassword();
        if (username == null || password == null || confirmPassword == null) {
            throw new RuntimeException("参数不能为空");
        }
        if (!password.equals(confirmPassword)) {
            throw new RuntimeException("两次密码不一致");
        }

        if (lambdaQuery().eq(User::getUsername, username).one() != null) {
            throw new RuntimeException("用户名已存在");
        }
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        user.setCreateTime(LocalDateTime.now());
        user.setUpdateTime(LocalDateTime.now());
        boolean save = save(user);
        if (save) {
            return R.ok(ResponseEnum.SUCCESS);
        }


        return R.error(ResponseEnum.ERROR);

    }


}
